<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="部门编号" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入部门编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用状态" prop="useStatus">
        <el-select v-model="queryParams.useStatus" placeholder="请选择使用状态" clearable size="small">
          <el-option
            v-for="dict in useStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="区域代码" prop="sellingRegionCode">
        <el-select v-model="queryParams.sellingRegionCode" placeholder="请选择区域代码" clearable size="small">
          <el-option
            v-for="dict in sellingRegionCodeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="市场编号" prop="id">
        <el-select v-model="queryParams.id" placeholder="请选择市场编号" clearable size="small">
          <el-option
            v-for="dict in marketplaceIdOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['amz:shopAuth:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['amz:shopAuth:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['amz:shopAuth:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['amz:shopAuth:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="mini"
          :disabled="multiple"
          @click="handleSync"
          v-hasPermi="['amz:shopAuth:sync']"
        >同步订单</el-button>
      </el-col>

	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="shopAuthList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="业务员" align="center" prop="createBy" width="100"/>
      <el-table-column label="店铺名称" align="center" prop="shopName" width="" :show-overflow-tooltip="true" />
      <el-table-column label="部门编号" align="center" prop="deptId" />
      <!--<el-table-column label="卖家记号" align="center" prop="sellerId" />-->
      <el-table-column label="区域" align="center" prop="sellingRegionName" />
      <el-table-column label="站点" align="center" prop="marketplaceName" />
      <el-table-column label="拉取天数" align="center" prop="ordersPullDays" />
      <el-table-column label="使用状态" align="center" prop="useStatus" :formatter="useStatusFormat" />
      <el-table-column label="授权状态" align="center" prop="authStatus" :formatter="authStatusFormat" />
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="刷新令牌" align="center" prop="refreshToken" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleAuth(scope.row)"
            v-hasPermi="['amz:shopAuth:auth']"
          >授权</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['amz:shopAuth:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['amz:shopAuth:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店铺授权对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" :close-on-click-modal="false" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺名称" prop="shopCode">
          <el-select v-model="form.shopCode" :disabled="disableFields" placeholder="请输入店铺名称">
            <el-option
              v-for="shop in shopCodeOptions"
              :key="shop.shopCode"
              :label="shop.shopName"
              :value="shop.shopCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卖家记号" prop="sellerId">
          <el-input v-model="form.sellerId" :disabled="disableFields" placeholder="请输入卖家记号" />
        </el-form-item>
        <el-form-item label="区域代码" prop="sellingRegionCode">
          <el-select v-model="form.sellingRegionCode" :disabled="disableFields" placeholder="请选择区域代码">
            <el-option
              v-for="dict in sellingRegionCodeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用状态" prop="useStatus">
          <el-select v-model="form.useStatus" placeholder="请选择使用状态">
            <el-option
              v-for="dict in useStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="授权状态" prop="authStatus">
          <el-select v-model="form.authStatus" placeholder="请选择授权状态">
            <el-option
              v-for="dict in authStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="拉取天数" prop="ordersPullDays">
          <el-input v-model="form.ordersPullDays" placeholder="请输入拉取天数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--店铺授权-->
    <el-dialog v-loading="loading" :title="title" :visible.sync="openDialogAuth" width="60%" :close-on-click-modal="false" append-to-body>
      <el-form ref="formAuth" :model="formAuth" :rules="rulesAuth" label-width="80px">

        <div>确保在安全的网络环境下操作，且登录的ERP与亚马逊后台在同一网络环境下，同时登录至需授权的站点</div>
        <br>
        <br>
        <div>操作一：在已登录亚马逊后台站点的浏览器地址输入以下授权链接，执行</div>
        <br>
        <div><span>{{formAuth.spapi_Auth_Url}}</span></div>
        <br>
        <br>
        <div>操作二：选中同意协议复选框，点击Confirm后，浏览器导航链接将会重定向，将重定向后的浏览器链接复制</div>
        <br>
        <br>
        <div>操作三：粘贴上一步重定向后的浏览器链接输入复制在下方，点击提交即可</div>
        <br>
        <br>
        <el-form-item label="重定向地址" prop="spapi_oauth_code_url">
          <el-input v-model="formAuth.spapi_oauth_code_url" type="textarea" placeholder="请输入确认授权后重定向地址" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="executeAuth">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listShopAuth, getShopAuth, delShopAuth, addShopAuth, updateShopAuth, exportShopAuth,getShopCodeByUsername,getSpapiAuthUrl,executeAuth,syncOrder } from "@/api/amz/shopAuth";

export default {
  name: "ShopAuth",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 店铺授权表格数据
      shopAuthList: [],
      // 弹出层标题
      title: "",
      // 是否显示新增/修改弹出层
      open: false,
      //  是否显示店铺授权弹出层
      openDialogAuth: false,
      //  弹框店铺代码下拉禁用
      disableFields:false,
      // 使用状态字典
      useStatusOptions: [],
      // 授权状态字典
      authStatusOptions: [],
      // 区域代码字典
      sellingRegionCodeOptions: [],
      // 市场编号字典
      marketplaceIdOptions: [],
      //新增-店铺列表
      shopCodeOptions: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: null,
        useStatus: null,
        sellingRegionCode: null,
        id: null,
      },
      // 表单参数
      form: {},
      // 授权表单
      formAuth:{
        shopAuthId: null,
        sellingRegionCode: null,
        spapi_Auth_Url: null,
        spapi_oauth_code_url: null
      },
      // 新增/修改表单校验
      rules: {
        shopCode: [
          { required: true, message: "店铺代码不能为空", trigger: "blur" }
        ],
      },
      // 授权表单校验
      rulesAuth: {
        shopCode: [
          { required: true, message: "店铺代码不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.getList();

    this.getDicts("amz_status").then(response => {
      this.useStatusOptions = response.data;
    });
    this.getDicts("amz_status").then(response => {
      this.authStatusOptions = response.data;
    });
    this.getDicts("amz_region_code").then(response => {
      this.sellingRegionCodeOptions = response.data;
    });
    this.getDicts("amz_marketplace_id").then(response => {
      this.marketplaceIdOptions = response.data;
    });

  },
  methods: {
    /** 查询店铺授权列表 */
    getList() {
      this.loading = true;
      listShopAuth(this.queryParams).then(response => {
        this.shopAuthList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 使用状态字典翻译
    useStatusFormat(row, column) {
      return this.selectDictLabel(this.useStatusOptions, row.useStatus);
    },
    // 授权状态字典翻译
    authStatusFormat(row, column) {
      return this.selectDictLabel(this.authStatusOptions, row.authStatus);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.openDialogAuth = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        shopAuthId: null,
        shopCode: null,
        shopName: null,
        deptId: null,
        useStatus: null,
        authStatus: null,
        sellerId: null,
        sellingRegionCode: null,
        sellingRegionName: null,
        marketplaceId: null,
        marketplaceName: null,
        refreshToken: null,
        accessToken: null,
        ordersPullDays: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.formAuth = {
        shopAuthId: null,
        sellingRegionCode: null,
        spapi_Auth_Url: null,
        spapi_oauth_code_url: null
      };
      this.resetForm("form");
    },
    //搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    //重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.shopAuthId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    //新增按钮操作
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加店铺授权";
      this.disableFields = false;//弹框店铺代码下拉禁用
      //获取当前登录人可添加的店铺信息
      this.getShopCodeByUsername();
    },
    //店铺授权/新增-通过当前登录人获取已维护的店铺
    getShopCodeByUsername(){
      getShopCodeByUsername().then(response => {
        this.shopCodeOptions = response.data;
      });
    },
    //修改按钮操作
    handleUpdate(row) {
      this.reset();
      const shopAuthId = row.shopAuthId || this.ids
      getShopAuth(shopAuthId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺授权";
        this.disableFields = true;//弹框店铺代码下拉禁用
      });
    },
    //授权按钮操作
    handleAuth(row) {
      this.reset();
      this.formAuth.shopAuthId = row.shopAuthId;
      this.formAuth.sellingRegionCode = row.sellingRegionCode;

      //通过区域代码获取spapi授权地址
      getSpapiAuthUrl(this.formAuth.sellingRegionCode).then(response => {
        this.formAuth.spapi_Auth_Url = response.msg;
        this.openDialogAuth = true;
        this.title = "店铺授权";
      });
    },
    //执行授权
    executeAuth() {
      this.$refs["formAuth"].validate(valid => {
        if (valid) {
          this.loading = true;
          executeAuth(this.formAuth).then(response => {
            this.msgSuccess(response.msg);
            this.openDialogAuth = false;
            this.getList();
            this.loading = false;
          }).catch((res) => {
            this.loading = false;
          })
        }
      });
    },
    //** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.shopAuthId == null) {
            let sellingRegionCodeOptionsChecked = this.sellingRegionCodeOptions.find((item) => {
              return item.dictValue === this.form.sellingRegionCode;
            });
            this.form.sellingRegionName = sellingRegionCodeOptionsChecked.dictLabel;

            let shopCodeOptionsChecked = this.shopCodeOptions.find((item) => {
              return item.shopCode === this.form.shopCode;
            });
            this.form.shopName = shopCodeOptionsChecked.shopName;

            addShopAuth(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          } else {
            updateShopAuth(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    //** 删除按钮操作 */
    handleDelete(row) {
      const shopAuthIds = row.shopAuthId || this.ids;
      this.$confirm('是否确认删除店铺授权编号为"' + shopAuthIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delShopAuth(shopAuthIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    //** 同步订单按钮操作 */
    handleSync(row) {
      const shopAuthIds = row.shopAuthId || this.ids;
      this.$confirm('是否确认同步订单,店铺授权编号为"' + shopAuthIds + '"的数据项?', {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return syncOrder(shopAuthIds);
        }).then(response => {
          console.log(response);
          this.msgSuccess(response.msg);
      })
    },
    //** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有店铺授权数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportShopAuth(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
